﻿// Decompiled with JetBrains decompiler
// Type: Netick.UnreliableChannel`1
// Assembly: Netick, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 6726ECA1-C773-4CF7-8952-E81B30D93B52
// Assembly location: D:\WorkSpaceDemo\UPM\NetickForUnity\Netick\Runtime\Netick.dll
// XML documentation location: D:\WorkSpaceDemo\UPM\NetickForUnity\Netick\Runtime\Netick.xml

using System.Collections.Generic;

#nullable disable
namespace Netick;

internal abstract class UnreliableChannel<T> : NetworkChannel where T : ISerializableMessage
{
  private Queue<T> _outgoingMsgs = new Queue<T>(256 /*0x0100*/);

  public UnreliableChannel(NetickEngine engine, NetworkConnection connection)
    : base(engine, connection)
  {
  }

  public override void Reset()
  {
    while (this._outgoingMsgs.Count > 0)
      this._outgoingMsgs.Dequeue().UnregisterConnection(this.Connection);
  }

  public void EnqueueMsg(T msg)
  {
    msg.RegisterConnection(this.Connection, 1);
    this._outgoingMsgs.Enqueue(msg);
  }

  public override void Write(BitBuffer buffer)
  {
    uint num1 = 0;
    int writePos = buffer.WritePos;
    int num2 = this.Engine.Config.MaxDataPerConnectionPerTickInBytes - 100;
    buffer.Add(20, 0U);
    while (this._outgoingMsgs.Count > 0)
    {
      T obj1 = this._outgoingMsgs.Peek();
      if (buffer.Length() + obj1.SizeBytes >= num2)
      {
        this._outgoingMsgs.Dequeue().RegisterSent(this.Connection);
        if (this.Engine.IsLoggingEnabled)
          NetickLogger.LogWarning(this.Engine, (object) "Dropping unreliable RPC due to not enough space to write it, consider increasing MaxSendableDataSize in Netick Settings, or sending less data per tick.");
      }
      else
      {
        T obj2 = this._outgoingMsgs.Dequeue();
        obj2.Write(this.Connection, buffer);
        obj2.RegisterSent(this.Connection);
        ++num1;
      }
    }
    buffer.Insert(writePos, 20, num1);
  }

  public override void Read(BitBuffer buffer)
  {
    uint num = buffer.Read(20);
    for (int index = 0; (long) index < (long) num; ++index)
    {
      int msgId = buffer.ReadInt4();
      this.Read(buffer, msgId, true);
    }
  }

  protected abstract void Read(BitBuffer buffer, int msgId, bool invoke);
}
